package com.bootcamp.javase2.synchro.SSX;

/**
 * @program: day20Sycn
 * @description:
 * @author: Keyu Li
 * @create: 2021-09-15 08:54
 **/

public class PrintNumSXX {
    public static void main(String[] args) {
        Num Number = new Num();
        PrintEven pe = new PrintEven(Number);
        PrintOdd po = new PrintOdd(Number);
        new Thread(pe).start();
        new Thread(po).start();
    }
}

class Num {
    int num = 0;

    public void odd() throws InterruptedException {
        synchronized (this) {
            if (num % 2 != 0){
                System.out.println("odd wait");
                this.wait();
            }
            else {
                System.out.println("偶数打印了"+num);
                num++;
                this.notifyAll();
            }
        }

    }

    public void even() throws InterruptedException {
        synchronized (this) {
            if (num % 2 == 0){
                System.out.println("even wait");
                this.wait();
            }
            else {
                System.out.println("奇数打印了"+num);
                num++;
                Thread.sleep(1000);
                System.out.println("even sleep over!!!");
                this.notifyAll();
            }
        }
    }
}

class PrintOdd implements Runnable {
    Num n;

    public PrintOdd(Num n) {
        this.n = n;
    }


    @Override
    public void run() {
        try {
            while (n.num < 100) {
                this.n.odd();
//                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class PrintEven implements Runnable {
    Num n;

    public PrintEven(Num n) {
        this.n = n;
    }

    @Override
    public void run() {
        try {
            while (n.num < 100)
                this.n.even();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
